#include <user_manager.h>

bool UserManager::addUser(const std::shared_ptr<FTPUser>& user)
{
	if (user == nullptr)return false;
	users_[user->getUsername()] = user;
	return true;
}

bool UserManager::exist(const std::string& username)
{
	return users_.find(username) != users_.end();
}

bool UserManager::userLogin(const std::string& username, const std::string& password)
{
	if (exist(username) && users_[username]->getPassword() == password) {
		// 限制单个user最大创建session的数量
		auto& cnt = userLoginCntMap_[username];
		if (cnt < MAX_LOGIN_COUNT) {
			std::lock_guard<std::mutex> lock(userCntLock_);
			if (cnt < MAX_LOGIN_COUNT) {
				++cnt;
				return true;
			}
		}
	}
	return false;
}

std::shared_ptr<FTPUser> UserManager::getUser(const std::string& username)
{
	if (users_.find(username) == users_.end()) {
		return nullptr;
	}
	return users_[username];
}

bool UserManager::userQuit(const std::string& username)
{
	--userLoginCntMap_[username];
	return true;
}

void UserManager::removeUser(const std::string& username)
{
	users_.erase(username);
}

UserManager& UserManager::instance()
{
	static UserManager instance;
	return instance;
}
